<template>
	<view>
		<!-- 标签框 -->
		<block v-if="imStatus == 0">
			<view class="top">
				<text></text>
				{{connnect_time}}分内医生未回复将自动退诊
			</view>
		</block>
		<block v-if="imStatus == 1">
		<view class="top2">
			<text></text>
			正在咨询中，此咨询将在{{connnect_time2}}分钟后结束
		</view>
		</block>
		<block v-if="imStatus == 2">
		<view class="top">
			<text></text>
			本次咨询已结束
		</view>
		</block>
		<view class="hz_info" @tap="toHz">
			<text>{{hz_info}}</text>
			<text>查看病人详情 > </text>
		</view>
		<view class="content" @touchstart="hideDrawer">
			<scroll-view class="msg-list" scroll-y="true" :scroll-with-animation="scrollAnimation" :scroll-top="scrollTop" :scroll-into-view="scrollToView" @scrolltoupper="loadHistory" upper-threshold="50" style="top: 5rem;">
				<!-- 加载历史数据waitingUI -->
				<block v-if="isHistoryLoading == true">
					<view class="loading">
						<view class="spinner">
							<view class="rect1"></view>
							<view class="rect2"></view>
							<view class="rect3"></view>
							<view class="rect4"></view>
							<view class="rect5"></view>
						</view>
					</view>
				</block>

				<view class="row" v-for="(row,index) in msgList" :key="index" :id="'msg'+row.msg.id">
					<!-- 系统消息 -->
					<block v-if="row.type=='system'" >
						<view class="system">
							<!-- 待接诊 -->
							<view v-if="row.msg.type=='djz'" class="dai_jie_zhen">{{row.msg.content.text}}</view>
							<!-- 已接诊 -->
							<view v-if="row.msg.type=='yjz'" class="yi_jie_zhen">{{row.msg.content.text}}</view>
							<!-- 接诊结束 -->
							<view v-if="row.msg.type=='jzjs'" class="jie_shu">
								<view class="jie_shu-msg">{{row.msg.content.text}}</view>
								<view class="jie_shu-close">x</view>
								<view class="jie_shu-evaluate">写评价</view>
							</view>
							<!-- 时间 -->
							<view v-if="row.msg.type=='time'" class="time">{{row.msg.content.text}}</view>
						</view>
					</block>
					<!-- 用户消息 -->
					<block v-if="row.type=='user'">
						<!-- 自己发出的消息 -->
						<view class="my" v-if="row.msg.userinfo.uid==myuid">
							<!-- 左-消息 -->
							<view class="left">
								<!-- 文字图片 -->
								<view class="msg" v-if="row.msg.type=='text'" @tap="toMap">
									<rich-text :nodes="row.msg.content.text"></rich-text>
								</view>
								<!-- 用户名称-时间-消息 -->
								<!-- <view class="username">
									<view class="name">{{row.msg.userinfo.username}}</view> <view class="time">{{row.msg.time}}</view>
								</view> -->
								<!-- 文字消息 -->
								<!-- <view v-if="row.msg.type=='text'" class="bubble" @tap="toMap">
									<rich-text :nodes="row.msg.content.text"></rich-text>
								</view> -->
								<!-- 语言消息 -->
								<view v-if="row.msg.type=='voice'" class="bubble voice" @tap="playVoice(row.msg)" :class="playMsgid == row.msg.id?'play':''">
									<view class="length">{{row.msg.content.length}}</view>
									<view class="icon my-voice"></view>
								</view>
								<!-- 图片消息 -->
								<view v-if="row.msg.type=='img'" class="bubble img" @tap="showPic(row.msg)">
									<image :src="row.msg.content.url" :style="{'width': row.msg.content.w+'px','height': row.msg.content.h+'px'}"></image>
								</view>
								<!-- 电子处方 -->
								<view v-if="row.msg.type=='dzcf'" class="msg msg-cf" @tap="toCf(row.msg.content.cf_id)">
									<view class="title">
										<image src="/static/message/static/message/cf-icon.png" mode="widthFix">
											<text>电子处方</text>
									</view>
									<view class="content">
										<view class="content-line" v-for="(item,i) in row.msg.content.list" :key="i">
											<text>{{item.name}}</text>
											<text>{{item.value}}</text>
										</view>
										<!-- <view class="content-btn">
											<view class="yao_fang">领取药方</view>
										</view> -->
									</view>
								</view>
							</view>
							<!-- 右-头像 -->
							<view class="right" @tap="toUserInfo(taskUserInfo)">
								<image :src="row.msg.userinfo.faceImg"></image>
							</view>
						</view>

						<!-- 别人发出的消息 -->
						<view class="other" v-if="row.msg.userinfo.uid!=myuid">
							<!-- 左-头像 -->
							<view class="left" @tap="toFriendInfo(row.msg.userinfo)">
								<image :src="taskUserInfo.faceImg ? taskUserInfo.faceImg : row.msg.userinfo.faceImg"></image>
							    <!-- <image v-if="isGroup" @click="toFriendInfo(row.msg.userinfo)" :src="row.msg.userinfo.faceImg"></image>
								<image v-else @click="toFriendInfo(row.msg.userinfo)" :src="taskUserInfo.faceImg"></image>
							 -->
							</view>
							<!-- 右-用户名称-时间-消息 -->
							<view class="right">
								<!-- <view class="username">
									<view class="name">{{taskUserInfo.userName ? taskUserInfo.userName :row.msg.userinfo.username}}</view>
									<view class="time">{{row.msg.time}}</view>
								</view> -->
								<!-- 文字消息 -->
								<view v-if="row.msg.type=='text'" class="msg" @tap="toMap">
									<rich-text :nodes="row.msg.content.text"></rich-text>
								</view>
								<!-- 语音消息 -->
								<view v-if="row.msg.type=='voice'" class="bubble voice" @tap="playVoice(row.msg)" :class="playMsgid == row.msg.id?'play':''">
									<view class="icon other-voice"></view>
									<view class="length">{{row.msg.content.length}}</view>
								</view>
								<!-- 图片消息 -->
								<view v-if="row.msg.type=='img'" class="bubble img" @tap="showPic(row.msg)">
									<image :src="row.msg.content.url" :style="{'width': row.msg.content.w+'px','height': row.msg.content.h+'px'}"></image>
								</view>
							</view>
						</view>
					</block>
				</view>

				<view>1假装有聊天记录</view>
				<view>2假装有聊天记录</view>
				<view>3假装有聊天记录</view>
				<view>4假装有聊天记录</view>
				<view>5假装有聊天记录</view>
				<view>6假装有聊天记录</view>
				<view>7假装有聊天记录</view>
				<view>8假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>假装有聊天记录</view>
				<view>aaaaaaaaaaaaaaaa</view>
				<view>bbbbbbbbbbbbbbbb</view>
				<view>cccccccccccccccc</view>
				<view>dddddddddddddddd</view>
			</scroll-view>
		</view>
		<!-- 抽屉栏 -->
		<view class="popup-layer" :class="popupLayerClass" @touchmove.stop.prevent="discard">
			<!-- 表情 -->
			<swiper class="emoji-swiper"
			@animationfinish="moveend($event)"
			:class="{hidden:hideEmoji}"
			indicator-dots="true"
			duration="150"
			:current="dotsCurrent"
			style="height: 107%;">
				<swiper-item v-for="(page,pid) in emojiList" :key="pid">
					<view v-for="(em,eid) in page" :key="eid" @tap="addEmoji(em)">
						<image mode="widthFix" :src="'https://res.wx.qq.com/mpres/htmledition/images/icon/emotion/'+em.url" style="width: 1.8rem; float: left; margin: 0.5rem;"></image>
					</view>
				</swiper-item>
			</swiper>
			<!-- <emotion @addEmoji="addEmoji" :class="{hidden:hideEmoji}" ></emotion> -->
			<!-- 更多功能 相册-拍照-红包 -->
			<view class="more-layer" :class="{hidden:hideMore}">
				<view class="list">
					<view class="box" @tap="chooseImage">
						<view class="icon tupian2"></view>
					</view>
					<view class="box" @tap="camera">
						<view class="icon paizhao"></view>
					</view>
					<view class="box" @tap="chufang">
						<image class="chufang" src="/static/message/static/HM-chat/img/chufang.png"></image>
					</view>
				</view>
			</view>
		</view>
		<block v-if="imStatus == 0">
			<view class="bottom-btn" @tap="imRefuse">拒绝接诊</view>
			<view class="bottom-btn" @tap="imConnect">接诊</view>
		</block>
		<block v-if="imStatus == 1">
			<!-- 底部输入栏 -->
			<view class="input-box" :class="popupLayerClass" @touchmove.stop.prevent="discard">
				<view class="bottom-btn2" @tap="imChose(1)">完成接诊</view>
				<view class="voice">
					<view class="icon" :class="isVoice?'jianpan':'yuyin'" @tap="switchVoice"></view>
				</view>
				<view class="textbox">
					<view class="voice-mode" :class="[isVoice?'':'hidden',recording?'recording':'']" @touchstart="recordBegin" @touchmove.stop.prevent="voiceIng" @touchend="voiceEnd" @touchcancel="voiceCancel">{{voiceTis}}</view>
					<view class="text-mode"  :class="isVoice?'hidden':''">
						<view class="box">
							<textarea auto-height="true" v-model="textMsg" @focus="textareaFocus"/>
						</view>
						<view class="em" @tap="chooseEmoji">
							<!-- <view class="icon biaoqing"></view> -->
							<image :src="chooseEmojiImg"
							style="width: 32px; height:32px;"></image>
						</view>
					</view>
				</view>
				<!-- #ifndef H5 -->
				<view class="more" @tap="showMore">
					<view class="icon add"></view>
				</view>
				<!-- #endif -->
				<view class="send" :class="isVoice?'hidden':''" @tap="sendText">
					<view class="btn">发送</view>
				</view>
			</view>
		</block>

		<!-- 录音UI效果 -->
		<view class="record" :class="recording?'':'hidden'">
			<view class="ing" :class="willStop?'hidden':''"><view class="icon luyin2" ></view></view>
			<view class="cancel" :class="willStop?'':'hidden'"><view class="icon chehui" ></view></view>
			<view class="tis" :class="willStop?'change':''">{{recordTis}}</view>
		</view>
    <uni-popup ref="popup" :type="type" @change="change">{{ content }}</uni-popup>
	</view>
</template>
<script>
	// import emotion from '@/static/message/chat/Message.js'
	// import emojiData from "@/static/message/static/emoji/emojiData.js"
	// import helper from '@/common/chat/helper.js';

	// import uniPopup from '@/static/message/components/uni-popup-im/uni-popup.vue'

	export default {
		components: {
			// emotion,
			// uniPopup
		},
		data() {
			return {
				//订单ID
				order_id: 0,
				//订单号
				orderNo: '',
				//患者id
				userId: '',
				//文字消息
				// dotsCurrent:1,
				//患者头像
				userFace:'',
				//患者昵称
				currentUser:"",
				//医生信息
				taskUserInfo:{
					userId: '',
					userName: '',
					faceImg: ''
				},

				longitude:'',
				latitude:'',
				address: '',

				controls: [{
				    id: 1,
				    position: {
				        left: 5,
				        top: 5,
				        width: 30,
				        height: 30
				    },
				    iconPath: '/static/message/static/HM-chat/img/logo.png',
				    clickable: true
				}],
				show: false,
				type: '',
				list: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
				content: '顶部弹 popup',
				bottomData: [],
				textMsg:'',
				mapPath:'/static/message/static/HM-chat/img/map.png',
				mapContent:null,
				chooseEmojiImg:"/static/message/static/HM-chat/img/mq_ic_emoji_normal.png",
				//消息列表
				isHistoryLoading:false,
				scrollAnimation:false,
				scrollTop:0,
				scrollToView:'',
				msgList:[],
				msgImgList:[],
				myuid:0,

				//录音相关参数
				// #ifndef H5
				//H5不能录音
				RECORDER:uni.getRecorderManager(),
				// #endif
				isVoice:false,
				voiceTis:'按住 说话',
				recordTis:"手指上滑 取消发送",
				recording:false,
				willStop:false,
				initPoint:{identifier:0,Y:0},
				recordTimer:null,
				recordLength:0,

				//播放语音相关参数
				AUDIO:uni.createInnerAudioContext(),
				playMsgid:null,
				VoiceTimer:null,
				// 抽屉参数
				popupLayerClass:'',
				// more参数
				hideMore:true,
				//表情定义
				hideEmoji:true,
				emojiList:[{}],
				emojiPath:'https://res.wx.qq.com/mpres/htmledition/images/icon/emotion/',

				isGroup: false,
				//是否连接
				socketOpen: false,
				//页码
				page: 1,
				limit: 10,
				msgHistoryList: [],

				//状态: 0=代接诊 1=接诊中 2=结束
				imStatus: 1,

				//心跳
				intervalID: 0,
				intervalID2: 0,
				is_connection: false,

				//患者信息
				hz_info: '',

				//时间
				msgLastTime: '',

				//连接时长
				intervalID3: 0,
				connnect_time: 0,
				connnect_time2: 0,

				//处方参数
				cf_id: 0,
				diagnose: '',
				goods_ids: ''
			};
		},
		onReady() {

		},
		onLoad(option) {
			//页面带过的参数
			option.userId = 'HZ_' + option.userId;
			option.sex = (option.sex == 1) ? '男' : '女';
			//状态:normal=正常,refund=已退款,cancel=已取消,refuse_patient=拒绝接诊,patient=接诊,end=完成接诊,comment=已评论
			switch(option.status){
				case 'normal':
					this.imStatus = 0;
					break;
				case 'patient':
					this.imStatus = 1;
					break;
				case 'refund':
				case 'cancel':
				case 'refuse_patient':
				case 'end':
				case 'comment':
					this.imStatus = 2;
					break;
			}
			console.log(this.imStatus);
			this.initMsgList(option)
		},
		onShow(){
			console.log('监听页面显示')
			this.sendCf();
			this.scrollTop = 9999999;
		},
		onHide(){
			console.log('监听页面隐藏');
		},
		onUnload(){
			console.log('监听页面卸载');
			clearInterval(this.intervalID)
			clearInterval(this.intervalID2)
			clearInterval(this.intervalID3)
			this.imChose()
			uni.closeSocket()
		},
		methods:{
			//删除聊天系统信息
			delMsgSystem(type){
				var that = this;
				for(var i=0;i<that.msgList.length;i++){
					if(that.msgList[i].type == "system" && (that.msgList[i].msg.type == 'djz' || that.msgList[i].msg.type == 'yjz')){
						that.msgList.splice(i, 1);
					}
				}
			},
			// 时间字符处理
			timeForm(date) {
				var myDate;
				myDate = new Date(Date.parse(date.replace(/-/g, "/")));
				var hour = myDate.getHours();
				var minutes = myDate.getMinutes();
				if (minutes < 10) minutes = '0' + minutes;
				return this.thisTimeForm(hour, myDate) + ' ' + hour + ':' + minutes;
			},
			thisTimeForm(hour, time) {
				var hour = time.getHours();
				var minutes = time.getMinutes();
				var year = time.getYear(); //获取当前年份(2位)
				var month = time.getMonth() + 1; //获取当前月份(0-11,0代表1月)
				var day = time.getDate(); ////获取当前日(1-31)
				var thisDate = new Date();
				var thisyear = thisDate.getYear(); //获取当前年份(2位)
				var thismonth = thisDate.getMonth() + 1; //获取当前月份(0-11,0代表1月)
				var thisday = thisDate.getDate(); ////获取当前日(1-31)
				if (year == thisyear && month == thismonth && day == thisday) {
					if (hour < 6) {
						return "凌晨";
					} else if (hour < 9) {
						return "早上";
					} else if (hour < 12) {
						return "上午";
					} else if (hour < 14) {
						return "中午";
					} else if (hour < 17) {
						return "下午";
					} else if (hour < 19) {
						return "傍晚";
					} else if (hour < 22) {
						return "晚上";
					} else {
						return "夜里";
					}
				} else {
					var date3 = thisDate.getTime() - time.getTime();
					var years = Math.floor(date3 / (12 * 30 * 24 * 3600 * 1000));
					var leave = date3 % (12 * 30 * 24 * 3600 * 1000);
					var months = Math.floor(leave / (30 * 24 * 3600 * 1000));
					var leave0 = leave % (30 * 24 * 3600 * 1000);
					var days = Math.floor(leave0 / (24 * 3600 * 1000));
					if (years == 0 && months == 0 && days > 0 && days < 7) {
						switch (days) {
							case 1:
								return '昨天';
							case 2:
								return '前天';
							default:
								return "星期" + "日一二三四五六".charAt(time.getDay());
								break;
						}
					} else {
						if (months == 0 && years == 0 && days == 0) {
							return '昨天';
						}
						if (months < 10) months = '0' + months;
						if (days < 10) days = '0' + days;
						if (years == 0) {
							return months + '-' + days;
						} else {
							return '20' + years + '-' + months + '-' + days;
						}
					}
				}
			},
			imRefuse(){
				this.imStatus = 2;
				this.operation('dt2');
				this.delMsgSystem();
				let that = this;
				let token = uni.getStorageSync("token");
				if (token) {
					that.$Http({
						url: 'consultationRefusePatient',
						type: 'POST',
						data: {
							order_id: that.order_id
						}
					}).then(res => {
						console.log(res)
					})
				}else{
					uni.navigateTo({
						url: '/pages/my/index',
					})
				}
			},
			imChose(i=0){
				this.imStatus = 2;
				this.operation('dt2');
				this.delMsgSystem();
				if(i == 1){
					let that = this;
					let token = uni.getStorageSync("token");
					if (token) {
						that.$Http({
							url: 'consultationEndPatient',
							type: 'POST',
							data: {
								order_id: that.order_id
							}
						}).then(res => {
							console.log(res)
						})
					}else{
						uni.navigateTo({
							url: '/pages/my/index',
						})
					}
				}
			},
			imConnect(){
				this.imStatus = 1;
				this.operation('dt1');
				this.delMsgSystem();
				this.screenMsg({type:"system",msg:{id:0,type:"yjz",content:{text:"───── 问诊已开始，本次问诊可持续"+this.connnect_time+"分钟 ─────"}}});

				let that = this;
				let token = uni.getStorageSync("token");
				if (token) {
					that.$Http({
						url: 'consultationPatient',
						type: 'POST',
						data: {
							order_id: that.order_id
						}
					}).then(res => {
						console.log(res)
					})
				}else{
					uni.navigateTo({
						url: '/pages/my/index',
					})
				}

				if(this.connnect_time > 0){
					that.connnect_time2 = that.connnect_time
					clearInterval(that.intervalID3)
					that.intervalID3 = setInterval(function(){
						that.connnect_time2 = that.connnect_time2 - 1;
						if(that.connnect_time2 <= 0){
							clearInterval(that.intervalID3)
							that.imChose(1)
						}
					}, 60000)
				}
			},
			moveend(e){
			   if(e.detail.current===4){
					this.dotsCurrent=Object.assign(this.dotsCurrent,1)
				}
			},
			//操作发送
			operation(message){
				var msg = {};
				msg.cmd = 'operation';
				msg.data = {};
				msg.data.uid = this.userId;
				msg.data.to_id = this.taskUserInfo.userId;
				msg.data.message = message;
				this.onSend(JSON.stringify(msg));
			},
			initMsgList(option){
				var that = this;
				// var url=that.isGroup ? '/pagesA/test-chat/groupInfo/groupInfo':'/pagesA/test-chat/friendInfo/friendInfo';
				uni.setNavigationBarTitle({
					title: '患者 - ' + option.userName
				});
				that.hz_info = option.userName + ' ' + option.sex + ' ' + option.age + '岁';
				//自己的信息
				let token = uni.getStorageSync("token");
				if (token) {
					that.$Http({
						url: 'getUserInfo',
						type: 'POST',
						data: {}
					}).then(res => {
						that.currentUser = res.data.doctor_info.name;
						that.userFace = 'http://cdn.yingpaipay.com' + res.data.doctor_info.img;
						that.userId = 'DT_' + res.data.doctor_info.user_id;
						that.myuid = 'DT_' + res.data.doctor_info.user_id;
						that.orderNo = option.orderNo;
						that.order_id = option.order_id;
						//对方的信息
						that.taskUserInfo.userId = option.userId;
						that.taskUserInfo.userName = option.userName;
						that.taskUserInfo.faceImg = option.userFace;

						if(that.imStatus == 3){
							this.getChatLog();
						}else{
							//链接
							this.getMsgList();

							//掉线重连
							clearInterval(that.intervalID2)
							that.intervalID2 = setInterval(function(){
								if(that.is_connection == false){
									uni.closeSocket()
									that.msgList = [];
									that.getMsgList();
								}
							}, 5000)
							//语音自然播放结束
							this.AUDIO.onEnded((res)=>{
								this.playMsgid=null;
							});
							// #ifndef H5
							//录音开始事件
							this.RECORDER.onStart((e)=>{
								this.recordBegin(e);
							})
							//录音结束事件
							this.RECORDER.onStop((e)=>{
								this.recordEnd(e);
							})
							// #endif

							this.emojiList =emojiData.imgArr[1].emojiList
						}
					})
				}else{
					uni.navigateTo({
						url: '/pages/my/index',
					})
				}
			},
			toUserInfo:function(item){
				console.log(item)
			},
			toFriendInfo:function(item){
				console.log(item)
			},
			//添加表情
			addEmoji(em){
				console.log(em);
				this.textMsg += em.alt;
				// this.emojiList =emojiData.imgArr[em.groupIndex].emojiList
				// this.emojiPath =emojiData.imgArr[em.groupIndex].emojiPath
				// console.log(emojiList);
				// console.log(emojiPath);
				// if(em.minEmoji===false){
				// 	this.sendBigEmoji(em.emojiItem.url)
				// }else{
				//   // this.textMsg+=em.alt;
				//   this.textMsg+=em.emojiItem.alt;
				// }
			},
			//接受消息(筛选处理)
			screenMsg(msg){
				//计算时间
				if(msg.type == "user"){
					if(this.msgLastTime == ''){
						var date = this.timeForm(msg.msg.time)
						this.msgLastTime = msg.msg.time;
						this.screenMsg({type:"system",msg:{id:0,type:"time",content:{text:date}}});
					}else{
						var startTime = new Date(this.msgLastTime); // 开始时间
						var endTime = new Date(msg.msg.time); // 结束时间
						var gap = Math.floor((endTime - startTime) / 1000 / 60);	//相差分钟
						if(gap > 5){
							var date = this.timeForm(msg.msg.time)
							this.msgLastTime = msg.msg.time;
							this.screenMsg({type:"system",msg:{id:0,type:"time",content:{text:date}}});
						}
					}
				}
				//从长连接处转发给这个方法，进行筛选处理
				if(msg != undefined){
					if(msg.type=='system'){
						// 系统消息
						switch (msg.msg.type){
							case 'djz':
							case 'yjz':
							case 'time':
							case 'text':
								this.addSystemTextMsg(msg);
								break;
							case 'redEnvelope':
								this.addSystemRedEnvelopeMsg(msg);
								break;
						}
					}else if(msg.type=='user'){
						// 用户消息
						switch (msg.msg.type){
							case 'dzcf':
							case 'text':
								this.addTextMsg(msg);
								break;
							case 'voice':
								this.addVoiceMsg(msg);
								break;
							case 'img':
								this.addImgMsg(msg);
								break;
							case 'redEnvelope':
								this.addRedEnvelopeMsg(msg);
								break;
						}
						// console.log('用户消息');
						//非自己的消息震动
						if(msg.msg.userinfo.uid!=this.myuid){
							// console.log('振动');
							uni.vibrateLong();
						}
					}
					this.$nextTick(function() {
						// 滚动到底
						this.scrollToView = 'msg'+msg.msg.id
					});
				}else{
					console.log('消息类型错误');
				}
			},
			//触发滑动到顶部(加载历史信息记录)
			loadHistory(e){
				if(this.isHistoryLoading){
					return ;
				}
				this.isHistoryLoading = true;//参数作为进入请求标识，防止重复请求
				this.scrollAnimation = false;//关闭滑动动画
				if(this.msgList == []){
					let Viewid = 0;
				}else{
					let Viewid = this.msgList[0].msg.id;//记住第一个信息ID
				}

				var that = this;
				let list = [];
				uni.request({
					url: 'https://im.511lh.cn/index/index/getUserChatLog?is_load=1&orderno=' + that.orderNo + '&page=' + that.page + '&limit=' + that.limit, //仅为示例，并非真实接口地址。
					success: (res) => {
						if(res.data.code == 200){
							for(var i=0;i<res.data.data.length;i++){
								list.push(JSON.parse(res.data.data[i].message));
							}
							that.page++;

							// 获取消息中的图片,并处理显示尺寸
							for(let i=0;i<list.length;i++){
								if(list[i].type=='user'&&list[i].msg.type=="img"){
									list[i].msg.content = this.setPicSize(list[i].msg.content);
									this.msgImgList.unshift(list[i].msg.content.url);
								}
								list[i].msg.id = Math.floor(Math.random()*1000+1);
								this.msgList.unshift(list[i]);
							}
							//这段代码很重要，不然每次加载历史数据都会跳到顶部
							this.$nextTick(function() {
								this.scrollToView = 'msg'+Viewid;//跳转上次的第一行信息位置
								this.$nextTick(function() {
									this.scrollAnimation = true;//恢复滚动动画
								});
							});
						}
						this.isHistoryLoading = false;
					},
					fail:(res)=>{
						console.log('get失败');
					}
				});
			},
			// 加载初始页面消息
			getMsgList(){
				var that = this;
				uni.connectSocket({
				  url: 'wss://im.511lh.cn/socket/'
				});
				uni.onSocketOpen(function (res) {
					that.socketOpen = true;
					that.onOpen(res);
				});
				uni.onSocketMessage(function (res) {
					that.onMessage(res)
				});
				uni.onSocketError(function (res) {
					that.onError(res)
				});
				uni.onSocketClose(function (res) {
					that.onClose(res);
				});
			},
			onOpen(evt){
				console.log("连接成功");
				var that = this;
				that.is_connection = true;
				//患者连接上线
				var msg = {};
				msg.data = {};
				msg.cmd = 'kefuConnection';
				msg.data.orderno = that.orderNo;
				msg.data.visitor_id = that.taskUserInfo.userId;
				msg.data.kefu_code = that.userId;
				this.onSend(JSON.stringify(msg));
				//心跳
				clearInterval(that.intervalID)
				that.intervalID = setInterval(function(){
					that.heartbeat();
				}, 30000)
				//获取历史信息
				setTimeout(function(){
					that.getChatLog();
				},2000)
			},
			onClose(evt){
				console.log("断开连接");
				this.is_connection = false;
			},
			onMessage(evt){
				var obj = JSON.parse(evt.data);
				var that = this;
				var consultation_no_received = obj.data.consultation_no_received;
				if(consultation_no_received != '' && consultation_no_received != undefined){
					that.connnect_time = consultation_no_received
					that.connnect_time2 = consultation_no_received
					clearInterval(that.intervalID3)
					that.intervalID3 = setInterval(function(){
						that.connnect_time2 = that.connnect_time2 - 1;
						if(that.connnect_time2 <= 0){
							clearInterval(that.intervalID3)
							that.imChose(1)
						}
					}, 60000)
				}
				switch(obj.data){
					case 'hz0':
						this.imStatus = 0;
						this.delMsgSystem();
						this.screenMsg({type:"system",msg:{id:0,type:"djz",content:{text:"待接诊，"+this.connnect_time+"分后未接诊将自动退诊"}}});
						break;
					case 'hz1':
						this.imStatus = 1;
						this.delMsgSystem();
						this.screenMsg({type:"system",msg:{id:0,type:"yjz",content:{text:"───── 问诊已开始，本次问诊可持续"+this.connnect_time+"分钟 ─────"}}});
						break;
					case 'hz2':
						this.imStatus = 2;
						this.delMsgSystem();
						break;
				}
				var msg = obj.data.message;
				if(msg != '' && msg != undefined){
					this.screenMsg(JSON.parse(msg))
				}
			},
			onError(evt) {
				console.log("服务未开启");
				console.log(evt);
			},
			onSend(msg) {
				var that = this;
				if (that.socketOpen) {
					uni.sendSocketMessage({
						data: msg
					});
				} else {
					socketMsgQueue.push(msg);
				}
			},
			//心跳
			heartbeat(){
				var msg = {};
				msg.data = {};
				msg.cmd = 'heartbeat';
				msg.data.visitor_id = this.userId;
				msg.data.visitor_name = this.currentUser;
				msg.data.visitor_avatar = this.userFace;
				this.onSend(JSON.stringify(msg));
			},
			//获取聊天信息
			getChatLog(){
				var that = this;
				//获取聊天信息
				uni.request({
					url: 'https://im.511lh.cn/index/index/getUserChatLog?orderno=' + that.orderNo + '&page=' + that.page + '&limit=10', //仅为示例，并非真实接口地址。
					success: (res) => {
						if(res.data.code == 200){
							for(var i=0;i<res.data.data.length;i++){
								this.screenMsg(JSON.parse(res.data.data[i].message))
							}
						}
						if(that.imStatus == 0){
							this.screenMsg({type:"system",msg:{id:0,type:"djz",content:{text:"待接诊，"+this.connnect_time+"分后未接诊将自动退诊"}}});
						}
						that.page++;
					},
					fail:(res)=>{
						console.log('get失败');
					}
				});
			},
			//处理图片尺寸，如果不处理宽高，新进入页面加载图片时候会闪
			setPicSize(content){
				// 让图片最长边等于设置的最大长度，短边等比例缩小，图片控件真实改变，区别于aspectFit方式。
				let maxW = uni.upx2px(350);//350是定义消息图片最大宽度
				let maxH = uni.upx2px(350);//350是定义消息图片最大高度
				if(content.w>maxW||content.h>maxH){
					let scale = content.w/content.h;
					content.w = scale>1?maxW:maxH*scale;
					content.h = scale>1?maxW/scale:maxH;
				}
				return content;
			},
			//更多功能(点击+弹出)
			showMore(){
				this.isVoice = false;
				this.hideEmoji = true;
				this.chooseEmojiImg="/static/message/static/HM-chat/img/mq_ic_emoji_normal.png"
				if(this.hideMore){
					this.hideMore = false;
					this.openDrawer();
				}else{
					this.hideDrawer();
				}
			},
			// 打开抽屉
			openDrawer(){
				this.popupLayerClass = 'showLayer';
			},
			// 隐藏抽屉
			hideDrawer(){
				this.popupLayerClass = '';
				this.chooseEmojiImg="/static/message/static/HM-chat/img/mq_ic_emoji_normal.png"
				setTimeout(()=>{
					this.hideMore = true;
					this.hideEmoji = true;
				},150);
			},
			// 选择图片发送
			chooseImage(){
				this.getImage('album');
			},
			//拍照发送
			camera(){
				this.getImage('camera');
			},
			//开处方
			chufang(){
				uni.navigateTo({
					url: '/pagesA/prescript/list?familyId='+this.userId.split('_')[1]+'&doctorId='+this.taskUserInfo.userId.split('_')[1],
				})
			},
			//选照片 or 拍照
			getImage(type){
				let that = this
				this.hideDrawer();
				uni.chooseImage({
					sourceType:[type],
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: (res)=>{
						for(let i=0;i<res.tempFilePaths.length;i++){
							uni.uploadFile({
								url: that.$Config.http_static + 'api/common/uploader',
								filePath:res.tempFilePaths[i],
								name:'file',
								formData: {},
								success: (uploadFileRes) => {
									var obj = JSON.parse(uploadFileRes.data);
									if(obj.msg = "上传成功"){
										let msg = {url:obj.data.fullurl,w:500,h:500};
										this.sendMsg(msg,'img');
									}
								}
							});
						}
					}
				});
			},
			// 选择表情
			chooseEmoji(){
				this.hideMore = true;
				if(this.hideEmoji){
					this.hideEmoji = false;
					this.chooseEmojiImg="/static/message/static/HM-chat/img/mq_ic_emoji_active.png"
					this.openDrawer();
				}else{
					this.hideDrawer();
				}
			},
			//获取焦点，如果不是选表情ing,则关闭抽屉
			textareaFocus(){
				if(this.popupLayerClass=='showLayer' && this.hideMore == false){
					this.hideDrawer();
				}
			},
			// 发送文字消息
			sendText(){
				// uni.showToast({
				// 	title:'发送文本消息',
				// 	icon:"none"
				// })
				this.hideDrawer();//隐藏抽屉
				if(!this.textMsg){
					return;
				}
				let content = this.replaceEmoji(this.textMsg);
				let msg = {text:content}
				this.sendMsg(msg,'text');
				this.textMsg = '';//清空输入框
			},
			//替换表情符号为图片
			replaceEmoji(str){
				console.log(str)
				// 正则表达式匹配内容
				let replacedStr = str.replace(/\[([^(\]|\[)]*)\]/g,(item, index)=>{
					// console.log("item: " + item);
					for(let i=0;i<this.emojiList.length;i++){
						let row = this.emojiList[i];
						for(let j=0;j<row.length;j++){
							let EM = row[j];
							if(EM.alt==item){
								//在线表情路径，图文混排必须使用网络路径，请上传一份表情到你的服务器后再替换此路径
								//比如你上传服务器后，你的100.gif路径为https://www.xxx.com/emoji/100.gif 则替换onlinePath填写为https://www.xxx.com/emoji/
								// let onlinePath = 'https://s2.ax1x.com/2019/04/12/'
								// let imgstr = '<image src="'+onlinePath+this.onlineEmoji[EM.url]+'">';

								let onlinePath=this.emojiPath
								let imgstr = '<img style="width:24px;height:24px;" src="'+onlinePath+EM.url+'">';
								// console.log("imgstr: " + imgstr);
								return imgstr;
							}
						}
					}
				});
				return '<div style="align-items: center;word-wrap:break-word;">'+replacedStr+'</div>';
			},
			// 发送消息
			sendMsg(content,type){
				// let lastid = this.msgList[this.msgList.length-1].msg.id;
				//获取聊天记录最新的id发送消息
				var that = this;
				uni.request({
					url: 'https://im.511lh.cn/index/index/getScrollToView?orderno=' + that.orderNo,
					success: (res) => {
						console.log(res);
						if(res.data.code == 200){
							var myDate = new Date();
							var time = myDate.getFullYear()+'-'+(myDate.getMonth()+1)+'-'+myDate.getDate()+' '+myDate.getHours()+':'+myDate.getMinutes()+':'+myDate.getSeconds();
							var lastid = res.data.data;
							lastid++;
							var msg = {};
							msg.cmd = 'message';
							msg.data = {};
							msg.data.orderno = that.orderNo
							msg.data.from_name = that.currentUser
							msg.data.from_id = that.userId
							msg.data.from_avatar = that.userFace
							msg.data.to_id = that.taskUserInfo.userId
							msg.data.to_name = that.taskUserInfo.userName
							msg.data.to_avatar = that.taskUserInfo.faceImg
							msg.data.message = {type:'user',msg:{id:lastid,time:time,type:type,userinfo:{uid:that.userId,username:that.currentUser,faceImg: that.userFace},content:content}}
							// 发送消息
							that.onSend(JSON.stringify(msg))
						}
					},
					fail:(res)=>{
						console.log('get失败');
					}
				});
			},
			// 添加文字消息到列表
			addTextMsg(msg){
				this.msgList.push(msg);
			},
			// 添加语音消息到列表
			addVoiceMsg(msg){
				this.msgList.push(msg);
			},
			// 添加图片消息到列表
			addImgMsg(msg){
				msg.msg.content = this.setPicSize(msg.msg.content);
				this.msgImgList.push(msg.msg.content.url);
				this.msgList.push(msg);
			},
			addRedEnvelopeMsg(msg){
				this.msgList.push(msg);
			},
			// 添加系统文字消息到列表
			addSystemTextMsg(msg){
				this.msgList.push(msg);
			},
			// 预览图片
			showPic(msg){
				uni.previewImage({
					indicator:"none",
					current:msg.content.url,
					urls: this.msgImgList
				});
			},
			// 播放语音
			playVoice(msg){
				this.playMsgid=msg.id;
				this.AUDIO.src = msg.content.url;
				this.$nextTick(function() {
					this.AUDIO.play();
				});
			},
			// 录音开始
			voiceBegin(e){
				if(e.touches.length>1){
					return ;
				}
				this.initPoint.Y = e.touches[0].clientY;
				this.initPoint.identifier = e.touches[0].identifier;
				// this.RECORDER.start({format:"mp3"});//录音开始,
			},
			//录音开始UI效果
			recordBegin(e){
				this.recording = true;
				this.voiceTis='松开 结束';
				this.recordLength = 0;
				this.recordTimer = setInterval(()=>{
					this.recordLength++;
				},1000)
			},
			// 录音被打断
			voiceCancel(){
				this.recording = false;
				this.voiceTis='按住 说话';
				this.recordTis = '手指上滑 取消发送'
				this.willStop = true;//不发送录音
				// this.RECORDER.stop();//录音结束
			},
			// 录音中(判断是否触发上滑取消发送)
			voiceIng(e){
				if(!this.recording){
					return;
				}
				let touche = e.touches[0];
				//上滑一个导航栏的高度触发上滑取消发送
				if(this.initPoint.Y - touche.clientY>=uni.upx2px(100)){
					this.willStop = true;
					this.recordTis = '松开手指 取消发送'
				}else{
					this.willStop = false;
					this.recordTis = '手指上滑 取消发送'
				}
			},
			// 结束录音
			voiceEnd(e){
				if(!this.recording){
					return;
				}
				this.recording = false;
				this.voiceTis='按住 说话';
				this.recordTis = '手指上滑 取消发送'
				this.RECORDER.stop();//录音结束
			},
			//录音结束(回调文件)
			recordEnd(e){
				let that = this
				clearInterval(this.recordTimer);
				if(!this.willStop){
					// console.log("e: " + JSON.stringify(e));
					uni.uploadFile({
						url: that.$Config.http_static + 'api/common/uploader',
						filePath:e.tempFilePath,
						name:'file',
						formData: {},
						success: (uploadFileRes) => {
							var obj = JSON.parse(uploadFileRes.data);
							if(obj.msg = "上传成功"){
								let msg = {
									length:0,
									url:obj.data.fullurl
								}
								let min = parseInt(this.recordLength/60);
								let sec = this.recordLength%60;
								min = min<10?'0'+min:min;
								sec = sec<10?'0'+sec:sec;
								msg.length = min+':'+sec;
								this.sendMsg(msg,'voice');
							}
						}
					});
				}else{
					// console.log('取消发送录音');
				}
				this.willStop = false;
			},
			// 切换语音/文字输入
			switchVoice(){
				this.hideDrawer();
				this.isVoice = this.isVoice?false:true;
			},
			discard(){
				return;
			},
			playVideoAndAudio(data){
				// 隐藏抽屉
				this.hideDrawer()
				this.cancel('share')

				console.log(data)
				if(data===0){
					uni.navigateTo({
						url:"/pagesA/livepush/livepush"
					})
				}else if(data===1){
					uni.navigateTo({
						url:"/pagesA/livepull/livepull"
					})
				}else{
					uni.showToast({
						title: "待开发..."
					})
				}
			},
			yuyintonghua(){
				// uni.navigateTo({
				// 	url:"/pagesA/livepull/livepull"
				// })

				// uni.navigateTo({
				// 	url:"/pagesA/livepush/livepush"
				// })

				// uni.navigateTo({
				// 	url:"/pagesA/livepull/popup/popup"
				// })

				this.togglePopup('bottom', 'share')
			},
			togglePopup(type, open) {
				switch (type) {
					case 'top':
						this.content = '顶部弹出 popup'
						break
					case 'bottom':
						this.content = '底部弹出 popup'
						break
					case 'center':
						this.content = '居中弹出 popup'
						break
				}
				this.type = type
				if (open === 'tip') {
					this.show = true
				} else {
					this.$refs[open].open()
				}
			},
			cancel(type) {
				console.log(type)
				if (type === 'tip') {
					this.show = false
					return
				}
				this.$refs[type].close()
			},
			change(e) {
				console.log(e.show)
			},
			//添加处方消息
			sendCf(){
				var that = this;
				if(that.cf_id > 0){
					uni.request({
						url: 'https://im.511lh.cn/index/index/getCFData?diagnose=' + that.diagnose + '&goods_ids=' + that.goods_ids,
						success: (res) => {
							if(res.data.code == 200){
								var msg = {'list':res.data.data,'cf_id':that.cf_id}
								this.sendMsg(msg,'dzcf');
							}
						},
						fail:(res)=>{
							console.log('get失败');
						}
					});
				}
			},
			toHz(){
				uni.navigateTo({
					url: '/pagesA/my/seedinfo?type=tw&id=' + this.orderNo,
				})
			},
			toCf(cf_id){
				uni.navigateTo({
					url: '/pagesA/drug/info?id=' + cf_id,
				})
			}
		}
	}
</script>
<style lang="scss">
	// @import "@/static/message/static/HM-chat/css/style.scss";

	/* 底部分享 */
	.uni-share {
		background: #fff;
	}

	.uni-share-title {
		line-height: 60upx;
		font-size: 24upx;
		padding: 15upx 0;
		text-align: center;
	}

	.uni-share-content {
		display: flex;
		flex-wrap: wrap;
		padding: 15px;
	}

	.uni-share-content-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 25%;
		box-sizing: border-box;
	}

	.uni-share-content-image {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 60upx;
		height: 60upx;
		overflow: hidden;
		border-radius: 10upx;
	}

	.uni-share-content-image .image {
		width: 100%;
		height: 100%;
	}

	.uni-share-content-text {
		font-size: 26upx;
		color: #333;
		padding-top: 5px;
		padding-bottom: 10px;
	}

	.uni-share-btn {
		height: 90upx;
		line-height: 90upx;
		border-top: 1px #f5f5f5 solid;
		text-align: center;
		color: #666;
	}


</style>